package com.example.springbootsecurity.demos.handler;

import cn.hutool.json.JSONUtil;
import com.example.springbootsecurity.demos.common.Result;
import com.example.springbootsecurity.demos.exception.CaptchaException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author by jingwei
 * @version V1.0
 * @classname LoginFailureHandler
 * @description
 * @date 2023/12/4 16:47
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException authenticationException) throws IOException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();

        Result result;
        if (authenticationException instanceof CaptchaException) {
            result = Result.fail("验证码错误");
        } else {
            result = Result.fail("用户名或密码错误");
        }
        outputStream.write(JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
